const dbHelper = require("db-helper")
const db = uniCloud.database()
const {
	wxPubConfig
} = require("config")
const WxPubApi = require("wx-public-api")
const wxPubApi = new WxPubApi()
module.exports = {
	getWxPubToken: async () => {
		try {
			var tokenData = await dbHelper.getOne("t3ds-token", {
				platform: "weixin",
				appId: wxPubConfig.appId
			})
			if (!tokenData || tokenData.expirationTime < Date.now()) {
				//token过期，重新获取
				let tokenInfo = await wxPubApi.getToken();
				if (tokenData) {
					db.collection("t3ds-token").doc(tokenData._id).update({
						token: tokenInfo.access_token,
						expirationTime: Date.now() + tokenInfo.expires_in * 1000
					})
					tokenData.token = tokenInfo.access_token;
					tokenData.expirationTime = Date.now() + tokenInfo.expires_in * 1000;
					console.log("token更新成功");
				} else {
					tokenData = {
						platform: 'weixin',
						appId: wxPubConfig.appId,
						expirationTime: Date.now() + tokenInfo.expires_in * 1000,
						token: tokenInfo.access_token
					}
					await dbHelper.insert("t3ds-token", tokenData);
					console.log("token保存成功");
				}
			}
			return tokenData.token;
		} catch (e) {
			throw e;
		}
	}
}
